package com.tanhua.dubbo.utils;

import com.tanhua.domain.mongo.Sequence;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

/**
 * 自增工具类
 *
 * @author
 * @date 2021/01/24
 */
@Slf4j
@Component
public class IdSequeue {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 获取指定集合中自增序列值
     *
     * @param collName 集合名称
     * @return 自增的序列值
     */
    public Long getNextId(String collName) {
        Query query = new Query(Criteria.where("collName").is(collName));

        Update update = new Update();
        update.inc("seqId", 1);
        //设置选项
        FindAndModifyOptions options = new FindAndModifyOptions();
        //如果集合里没有此记录是否新增进去
        options.upsert(true);
        //是否修改后获取最新的值
        options.returnNew(true);

        Sequence sequence = mongoTemplate.findAndModify(query, update, options, Sequence.class);
        return sequence.getSeqId();
    }

}
